﻿using Microsoft.EntityFrameworkCore;
using Sgr.Domain.Entities.Auditing;
using Sgr.Domain.Repositories;
using Sgr.EntityFrameworkCore;
using Sgr.Exceptions;
using Sgr.Generator;
using Sgr.UPMS.Domain.Organizations;

namespace Sgr.UPMS.Infrastructure.Repositories
{
    public class OrganizationInvitationRepository<TDbContext> : EfCoreRepositoryOfTEntityAndTPrimaryKey<TDbContext, OrganizationInvitation, long>, IOrganizationInvitationRepository where TDbContext : UnitOfWorkDbContext
    {
        private readonly ISegmentNumIdGenerator _numberIdGenerator;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContextProvider"></param>
        /// <param name="auditedOperator">审计操作者</param>
        /// <param name="numberIdGenerator">数字ID生成器</param>
        /// <exception cref="BusinessException">参数为空时抛出异常</exception>
        public OrganizationInvitationRepository(
            IDbContextProvider<TDbContext> dbContextProvider,
            IAuditedOperator auditedOperator,
            ISegmentNumIdGenerator numberIdGenerator)
            : base(dbContextProvider, auditedOperator)
        {
            _numberIdGenerator = numberIdGenerator ?? throw new ArgumentNullException(nameof(numberIdGenerator));
        }

        public async Task<OrganizationInvitation?> GetByInvitationCodeAsync(string invitationCode, CancellationToken cancellationToken = default)
        {
            Check.StringNotNullOrEmpty(invitationCode, nameof(invitationCode));

            // 使用高效的查询方式获取资源
            var dbContext = await GetDbContextAsync(cancellationToken);
            return await dbContext.Set<OrganizationInvitation>()
                .Where(r => r.InvitationCode == invitationCode)
                .FirstOrDefaultAsync(cancellationToken);
        }

        /// <summary>
        /// 检查并设置主键Id
        /// </summary>
        /// <param name="entity">实体</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns></returns>
        protected override async Task CheckAndSetIdAsync(OrganizationInvitation entity, CancellationToken cancellationToken = default)
        {
            if (entity.Id == 0)
                entity.Id = await _numberIdGenerator.GetUniqueIdAsync(UpmsConstant.DEFAULT_SEGMENT_KEY, cancellationToken);
        }
    }
}